import React, { Component } from 'react';
import { Button, Form, Input } from 'antd';

class EditUser1 extends Component{
  constructor(props) {
    super(props);
    this.formRef = React.createRef();
  }

  componentWillReceiveProps(nextProps, nextContext) {
    console.log("nextProps",nextProps);
    if (nextProps.currentData.user_id!=this.props.currentData.user_id){
      this.formRef.current.setFieldsValue(nextProps.currentData);
      this.setState({
        currentData:nextProps.currentData,
      })
    }
  }

  componentDidMount() {
    console.log("componentDidMount");
    this.formRef.current.setFieldsValue(this.props.currentData);
    this.setState({
      currentData:this.props.currentData,
    })
  }

  onFinish=(values)=>{
    const url="http://localhost:8080/user";
    console.log(values);
    console.log(this.state.currentData);
    const sendData={...this.state.currentData,...values};
    console.log("sendData",sendData);
    fetch(url,
      {
        method:'PUT',
        body:JSON.stringify(sendData),
        headers: {
          "Content-Type": 'application/json',
          Authorization: localStorage.getItem('Authorization'),
        },
      })
      .then((response) => response.json())
      .then((res)=>{
        console.log(res);
        const {code=0}=res;
        if(code==0){
          this.props.refresh();
          this.props.closeDrawer();
        }
      })
  }

  render() {
    console.log(this.props);
    return(
      <>
        <Form
          onFinish={this.onFinish}
          ref={this.formRef}
        >

          <Form.Item
            name="username"
            label="姓名"
            rules={[
              {
                required:true,
                message: '请输入用户名称!',
              },
              {
                pattern:/^[a-zA-Z\u4e00-\u9fff]{3,20}$/,
                message: '只允许输入英文或中文',
              },
            ]}
          >
            <Input
              size="large"
              placeholder="请输入姓名"
            />
          </Form.Item>

          <Form.Item
            name="phone"
            label="联系电话"
            rules={[
              {
                required:true,
                message: '请输入电话!',
              },
              {
                pattern:/^1[3-9]\d{9}$/,
                message: '请输入正确的电话!',
              },
            ]}
          >
            <Input
              size="large"
              placeholder="请输入联系电话"
            />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              编辑
            </Button>
          </Form.Item>
        </Form>
      </>
    )
  }
}

export default EditUser1
